package com.example.algorithm.SelectAlgorithm;

/**
 * 二分查找法(数组必须有序)
 * Created by ZMJ on 2020/2/18.
 */
public class BinarySearch {

    /**
     * @param data 数据源
     * @param key  需要查找的关键字
     * @return
     */
    static Integer search(int[] data, int key) {
        int left = 0;
        int right = data.length;
        while (left < right) {
            int mid = (left + right) >> 1; // 除以2
            if (data[mid] == key) {
                return mid;
            } else if (key > data[mid]) {
                //说明查找的数据在右边
                left = mid + 1;
            } else if (key < data[mid]) {
                //说明查找的数据在左边
                right = mid - 1;
            }
        }
        return null;
    }

    public static void main(String args[]) {
        int[] arr = {1,2,3,4,5,6,7,8,9};
        Integer index = search(arr, 6);
        System.out.println("index:" + index);
    }

}
